package cc.ufinity.networkdiagnose.widget;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cc.ufinity.networkdiagnose.manager.MessageWhat;
import cc.ufinity.networkdiagnose.manager.NetworkManager;
import cc.ufinity.networkdiagnose.manager.Task;
import cc.ufinity.networkdiagnose.manager.TaskParser;
import cc.ufinity.networkdiagnose.manager.TelManager;
import cc.ufinity.networkdiagnose.util.StringUtils;
import cc.ufinity.networkdiagnose.view.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

public class Task_Test_Widget extends GeneralTestWidget {
	public final static String PREFS_NAME = "mymobile";
    public final static String PREFS_KEY = "number";
    private  Handler updateHandler;
	private Activity ctx;
    private boolean connecting;
	private static String TAG = "TaskWidget";
	private ListView taskListView;
	private List<Task> tasks = null;
	private TelManager tm;
	private Handler handler;
	private String myPhoneNumber;
	private List<Map<String, Object>> datas;
	private TaskTestListAdapter tAdapter = null;
	
	private ProgressBar pb1 = null, pb2 = null;
	private Button begin_test = null;
	private TextView tv_progress1 = null, tv_progress2 = null;
	private LinearLayout linearlayout = null; 
	private ImageView image = null;

	public Task_Test_Widget(Activity context) {
		super(context);
		this.ctx = context;
		
		Task task = (Task) ctx.getIntent().getSerializableExtra(TAG_REFER_TASK);//获取任务
		if(task == null) {
			System.out.println("task传值失败" );
		} else {
			System.out.println("网络类型：" + task.selNetType);
		}
		
		inflate(context, R.layout.task_test_widget, this);
		linearlayout = (LinearLayout)this.findViewById(R.id.progress_linearlayout);
		image = new ImageView(ctx);
		image.setBackgroundResource(R.drawable.ping);
		linearlayout.addView(image, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
		
	//	pb1 = (ProgressBar)findViewById(R.id.progress1);
		pb2 = (ProgressBar)findViewById(R.id.progress2);
		tv_progress1 = (TextView)findViewById(R.id.tv_progress1);
		tv_progress2 = (TextView)findViewById(R.id.tv_progress2);
		
		begin_test = (Button)findViewById(R.id.begin_tesk);
		begin_test.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				updateThread.start();
			}
		});
		
		taskListView = (ListView) this.findViewById(R.id.taskTestListView);
		taskListView.setOnItemClickListener(new OnItemClickListener() {

			@SuppressWarnings("unchecked")
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Map<String, Object> r = (Map<String, Object>) taskListView
						.getAdapter().getItem(position);
				
				Log.d("结果查看", "详细信息: " + r.toString());
				
				/*Task task = (Task) r.get("task");
				ctx.getIntent().putExtra(TAG_REFER_TASK, task);
				SelectNetType st = new SelectNetType(ctx);
				ctx.setContentView(st);*/
			}

		});
		
		/*handler = new Handler() {
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case MessageWhat.TASK_LIST_LOADED_SUCCESS:
					init();
					dismissMessageDialog();
					break;
				case MessageWhat.TASK_LIST_LOADED_FAILED:
					dismissMessageDialog();
					showMessage(ctx, "获取任务列表失败.");
					break;
				case 2:
					showMessage(ctx, "本机手机号码无法获取.");
					dismissMessageDialog();
					break;
				}
			}
		};
*/
		updateHandler = new Handler() {
			public void handleMessage(Message msg) {
				if(msg.arg1 == 0) {
					ProgressBar pb = new ProgressBar(ctx);
					pb.setVisibility(VISIBLE);
					linearlayout.removeAllViews();
					linearlayout.addView(pb, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
				}
				
				@SuppressWarnings("unchecked")
				Map<String, Object> t = (Map<String, Object>) taskListView
					.getAdapter().getItem(msg.arg1);
				
				
				if(t.get("taskSkip").equals("0")) {
					t.put("taskState", "1");
				} else if(t.get("taskSkip").equals("1")) {
					System.out.println(t.get("taskName") + " 已跳过");
				}
				
				tAdapter.notifyDataSetChanged();
				tv_progress1.setText("总进度：" + 100*(msg.arg1+1)/datas.size() + "%");
				tv_progress2.setText("正在检测第" + (msg.arg1+1) + "项：" + t.get("taskName"));
				
				if(msg.arg1+1 >= datas.size()) {
					tv_progress2.setText("检测完毕");
					linearlayout.removeAllViews();
					linearlayout.addView(image, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
				}
				
				pb2.setProgress(msg.arg1+1);
			}
		}; 
		tm = new TelManager(ctx);
		tm.setHandler(updateHandler); 
		start(); 
	}
	
	
	Thread updateThread = new Thread() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			System.out.println("开始测试...");
			System.out.println("测试项总数：" + datas.size());
			pb2.setMax(datas.size());
			for(int i=0; i<datas.size(); i++) {
				try {
					Thread.sleep(3000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				System.out.println("测试项序号：" + i);
				Message msg = new Message();
				msg.arg1 = i;
				updateHandler.sendMessage(msg);
			}
			
			System.out.println("结束测试...");
		}
		
	}; 
	public void start() {
		if (NetworkManager.detectNetworkConnectivity(ctx) == -1) {
			showMessage(ctx, "无法连接至因特网.");
			return;
		}
		 myPhoneNumber = tm.getPhoneNumber();
		if (StringUtils.isEmpty(myPhoneNumber)) {
			showMessage(ctx, "获取本机号码失败,请输入.");
			showInputDialog();
			return;
		} else {
			loadTaskList();
		}
	}

	private void showInputDialog() {
		LayoutInflater factory = LayoutInflater.from(ctx);
		final View dialogView = factory.inflate(
				R.layout.input_phone_num_dialog, null);
		final EditText inputText = (EditText) dialogView
				.findViewById(R.id.phoneNumEditText);
		AlertDialog.Builder inputBuilder = new AlertDialog.Builder(ctx);
		inputBuilder.setTitle("提示");
		inputBuilder.setIcon(R.drawable.smile);
		inputBuilder.setView(dialogView);
		inputBuilder.setPositiveButton("确定",
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						if (StringUtils.isEmpty(inputText.getText().toString())) {
							try {
								Field field = dialog.getClass().getSuperclass()
										.getDeclaredField("mShowing");
								field.setAccessible(true);
								field.set(dialog, false);
							} catch (Exception e) {
								e.printStackTrace();
							}
							showMessage(ctx, "请输入本机号码");

						} else {
							try {
								Field field = dialog.getClass().getSuperclass()
										.getDeclaredField("mShowing");
								field.setAccessible(true);
								field.set(dialog, true);
							} catch (Exception e) {
								e.printStackTrace();
							}
							myPhoneNumber = inputText.getText().toString();
							SharedPreferences settings = ctx.getSharedPreferences(PREFS_NAME, 0);
				            SharedPreferences.Editor editor = settings.edit();
				            editor.putString(PREFS_KEY, myPhoneNumber);
				            editor.commit();   //保存手机号码
				            
							dialog.cancel();
							loadTaskList();
						}
					}
				});
		inputBuilder.setNegativeButton("取消", 
				new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();
			}
		});
		Dialog dialog = inputBuilder.create();
		dialog.show();
	}

	private void loadTaskList() {
		this.showMessageDialog(ctx, "正在加载任务列表...");
		new Thread() {
			public void run() {
				getTasks();
			}
		}.start();
	}

	private void init() {
		
	/*	SimpleAdapter adapter = new SimpleAdapter(ctx, datas, R.layout.task_test_list_widget, 
				new String[] {"taskName"}, new int[] {R.id.task_name,});
		taskListView.setAdapter(adapter);
	*/	
		tAdapter = new TaskTestListAdapter(ctx, datas);
		taskListView.setAdapter(tAdapter);
	}
	
	private List<Map<String, Object>> getTasks() {
		List<Map<String, Object>> res = new ArrayList<Map<String, Object>>();

		try {
			tasks = new ArrayList<Task>();
			
			Task tk0 = new Task();  Task tk1 = new Task();
			Task tk2 = new Task();  Task tk3 = new Task();
			Task tk4 = new Task();  Task tk5 = new Task();
			Task tk6 = new Task();  Task tk7 = new Task();
			Task tk8 = new Task();  Task tk9 = new Task();
			Task tk = new Task();
			tk0.taskName = "信噪比测试";  tk1.taskName = "信号强度SRRI";
			tk2.taskName = "AP关联";  tk3.taskName = "隔离测试";
			tk4.taskName = "漫游测试";  tk5.taskName = "WEB认证";
			tk6.taskName = "PING测试";  tk7.taskName = "SIM认证";
			tk8.taskName = "PEAP认证";  tk9.taskName = "HTTP测试";
			tk.taskName = "FTP测试";  
			tasks.add(tk0);  tasks.add(tk1);
			tasks.add(tk2);  tasks.add(tk3);
			tasks.add(tk4);  tasks.add(tk5);
			tasks.add(tk6);  tasks.add(tk7);
			tasks.add(tk8);  tasks.add(tk9);
			tasks.add(tk);
			
			
			Map<String, Object> t = null;
			for (Task task : tasks) {
				t = new HashMap<String, Object>();
				t.put("taskName", task.taskName);
				t.put("taskState", "0");  //检测状态
				t.put("taskSkip", "0");   //是否跳过
				
				res.add(t);
			}
			datas = res;
			Message e = new Message();
			e.what = MessageWhat.TASK_LIST_LOADED_SUCCESS;
			handler.sendMessage(e);

		} catch (Exception e) {
			Log.e(TAG, "解析XML任务时出错：", e);
			Message e1 = new Message();
			e1.what = MessageWhat.TASK_LIST_LOADED_FAILED;
			handler.sendMessage(e1);
		}
		return res;
	}

}
